<template>
  <el-card shadow="hover" class="feedback-container">
    <!-- 搜索栏 -->
    <el-form
      :inline="true"
      :model="searchForm"
      class="search-form"
      style="margin-bottom: 10px"
    >
      <el-form-item label="疫苗编号">
        <el-input
          v-model="searchForm.vaccineNumbering"
          placeholder="输入疫苗编号"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="applyFilterAndSort">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 疫苗列表 -->
    <el-table
      :data="pageData"
      border
      style="width: 100%"
      v-loading="loading"
      highlight-current-row
    >
      <el-table-column
        label="序号"
        type="index"
        width="60"
        :index="(index) => (page - 1) * pageSize + index + 1"
      />
      <el-table-column prop="vaccineNumbering" label="疫苗编号" />
      <el-table-column prop="quantityUsed" label="领取数量" />
      <el-table-column
        prop="usageTime"
        label="领取时间"
        :formatter="formatDate"
      />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            :disabled="scope.row.hasFeedback"
            @click="handleFeedback(scope.row)"
          >
            {{ scope.row.hasFeedback ? '已反馈' : '反馈' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next, jumper"
      :total="filteredData.length"
      :page-size="pageSize"
      :current-page="page"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: right"
    />

    <!-- 反馈弹窗 -->
    <el-dialog
      title="疫苗反馈"
      v-model="feedbackDialogVisible"
      width="500px"
      :before-close="handleDialogClose"
    >
      <el-form :model="feedbackForm" ref="feedbackFormRef" label-width="100px">
        <el-form-item label="疫苗编号">
          <el-input v-model="feedbackForm.vaccineNumbering" disabled />
        </el-form-item>
        <el-form-item
          label="反馈内容"
          prop="feedbackText"
          :rules="[
            { required: true, message: '请输入反馈内容', trigger: 'blur' },
          ]"
        >
          <el-input
            type="textarea"
            rows="4"
            v-model="feedbackForm.feedbackText"
            placeholder="请输入您的反馈"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="feedbackDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitFeedback">提交反馈</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

// 医生信息
const doctor = JSON.parse(localStorage.getItem('user') || '{}')

// 全部领取数据（原始）
const allUsageData = ref([])
// 反馈数据
const feedbackList = ref([])
// 过滤后数据（查询后）
const filteredData = ref([])

const page = ref(1)
const pageSize = ref(5)
const loading = ref(false)

// 当前分页数据
const pageData = ref([])

const feedbackDialogVisible = ref(false)
const feedbackFormRef = ref(null)
const feedbackForm = reactive({
  vaccineNumbering: '',
  feedbackText: '',
})

const searchForm = reactive({
  vaccineNumbering: '',
})

// 格式化日期
const formatDate = (row, column, cellValue) =>
  cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm') : ''

// 拉取所有数据（一次性拉取全部）
const fetchAllData = async () => {
  loading.value = true
  try {
    // 拉取领取数据
    const usageRes = await axios.get(
      'http://127.0.0.1:8181/vaccineUsage/list',
      {
        params: { doctorId: doctor.id, page: 1, size: 1000 },
      }
    )
    allUsageData.value = usageRes.data.data.data || []

    // 拉取反馈数据
    const feedbackRes = await axios.get(
      'http://127.0.0.1:8181/vaccineFeedback/list',
      {
        params: { doctorId: doctor.id },
      }
    )
    feedbackList.value = feedbackRes.data.data || []

    // 标记是否已反馈
    const feedbackSet = new Set(
      feedbackList.value.map((f) => f.vaccineNumbering)
    )
    allUsageData.value = allUsageData.value.map((item) => ({
      ...item,
      hasFeedback: feedbackSet.has(item.vaccineNumbering),
    }))

    // 初始化过滤数据
    applyFilterAndSort()
  } catch (err) {
    console.error(err)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 应用过滤和排序
const applyFilterAndSort = () => {
  let list = [...allUsageData.value]

  // 疫苗编号模糊过滤
  if (searchForm.vaccineNumbering) {
    list = list.filter((item) =>
      item.vaccineNumbering.includes(searchForm.vaccineNumbering)
    )
  }

  // 可以加排序，比如按疫苗编号排序
  filteredData.value = list.sort((a, b) =>
    a.vaccineNumbering.localeCompare(b.vaccineNumbering)
  )

  page.value = 1
  updatePageData()
}

// 更新当前分页显示数据
const updatePageData = () => {
  const start = (page.value - 1) * pageSize.value
  const end = start + pageSize.value
  pageData.value = filteredData.value.slice(start, end)
}

const handlePageChange = (newPage) => {
  page.value = newPage
  updatePageData()
}

const resetSearch = () => {
  searchForm.vaccineNumbering = ''
  page.value = 1
  applyFilterAndSort()
}

const handleFeedback = (row) => {
  if (row.hasFeedback) {
    ElMessage.warning('该疫苗已反馈，无法重复反馈')
    return
  }
  feedbackForm.vaccineNumbering = row.vaccineNumbering
  feedbackForm.feedbackText = ''
  feedbackDialogVisible.value = true
}

const submitFeedback = () => {
  feedbackFormRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      await axios.post('http://127.0.0.1:8181/doctor/feedback', {
        vaccineNumbering: feedbackForm.vaccineNumbering,
        feedbackText: feedbackForm.feedbackText,
        doctorId: doctor.id,
        feedbackTime: dayjs().toISOString(),
      })
      ElMessage.success('反馈提交成功')
      feedbackDialogVisible.value = false
      await fetchAllData()
    } catch (err) {
      console.error(err)
      ElMessage.error('反馈提交失败')
    }
  })
}

const handleDialogClose = () => {
  feedbackDialogVisible.value = false
  feedbackFormRef.value?.clearValidate()
}

onMounted(fetchAllData)
</script>

<style scoped>
.feedback-container {
  padding: 20px;
}
.search-form {
  margin-bottom: 10px;
}
</style>
